from autosklearn.classification import AutoSklearnClassifier
from autosklearn.regression import AutoSklearnRegressor
from autosklearn.metrics import make_scorer
from apps.mlplatform.ml_handle.classification import get_X_Y_data, split_dataset
from apps.mlplatform.ml_handle.visualization import get_heatmap_path, get_feature_imp_path
from hte.error.models import HTEError
from hte.error.handle import abort_on_error
from sklearn import metrics


def auto_classfication(params):
    clf = AutoSklearnClassifier()
    clf.set_params(**params)
    return clf


def auto_regession(params):
    clf = AutoSklearnRegressor()
    clf.set_params(**params)
    return clf


def auto_class_result(task, clf, dataset):
    X, Y = get_X_Y_data(dataset, task.label, task.features)
    if Y is None:
        abort_on_error(HTEError.BAD_DATA)
    x_train, x_test, y_train, y_test = split_dataset(X, Y, 0.3)
    clf.fit(x_train, y_train)
    y_prediciton = clf.predict(x_test)
    socer = make_scorer('f1', metrics.f1_score(y_test, y_prediciton))
    print(socer)
    result = {}
    result['acc'] = metrics.accuracy_score(y_test, y_prediciton)
    imgs = []
    imgs.append(get_heatmap_path(X))
    imgs.append(get_feature_imp_path(X, Y))

    return result, imgs


def auto_class_imgs(task, dataset):
    X, Y = get_X_Y_data(dataset, task.label, task.features)
    imgs = []
    imgs.append(get_heatmap_path(X))
    imgs.append(get_feature_imp_path(X, Y))


def auto_reg_result(task, clf, dataset):
    X, Y = get_X_Y_data(dataset, task.label, task.features)
    if Y is None:
        abort_on_error(HTEError.BAD_DATA)
    x_train, x_test, y_train, y_test = split_dataset(X, Y, 0.3)
    clf.fit(x_train, y_train)
    result = {}

    result['score'] = clf.score(x_test, y_test)
    result['coef'] = list(clf.coef_)
    result['intercept'] = clf.intercept_
    imgs = []
    imgs.append(get_heatmap_path(X))
    return result, imgs


def auto_reg_imgs(task, dataset):
    X, Y = get_X_Y_data(dataset, task.label, task.features)
    imgs = []
    imgs.append(get_heatmap_path(X))
    return imgs


if __name__ == "__main__":
    params = {'time_left_for_this_task': 60, 'per_run_time_limit': 6,
              'include_estimators': ['svm']}
    clf = auto_classfication(params)
    print(clf)

